# coding=utf-8
import datetime
import hashlib
import random

import misaka as m
import requests
import tornado

from db.model import Article
from db.user import User
from libs.Tools import WashTools
from libs.Url import Url

# Create a custom renderer
from view import getMeta
from view.MarkdownRender import BleepRenderer
from view.MarkdownRender.ArticleParser import ArticleParser

extension_list = ['md']


class MainPage(tornado.web.RequestHandler):
    def get(self, path):
        meta = getMeta()
        if meta:
            qiniu_url = meta['domain']
            meta_title = meta['title']
            headico = meta['headico']
            auth_name = meta.get('auth_name', 'from ' + meta_title)
        else:
            self.redirect('/config')
            # db.close()
            return

        path = Url(path.encode('utf8'))
        path = path.addUrlStart()
        path = path.delUrlEnd()
        title = path.split('/')[-1]
        path += '.md'
        u_path = Url('/' + path)

        base_url = u_path.getUrlDir().delUrlStart()

        code, info, html = ArticleParser.getPageHTML(qiniu_url, path, base_url, title, refresh=False)

        if html == '':

            code, info, html = ArticleParser.getPageHTML(qiniu_url, path, base_url, title, refresh=True)
        if code == 200:
            self.render('main.html',
                        html=html,
                        hash_id=info['id'],
                        title=info['title'],
                        count=info['font_count'],
                        read_count=info['read_count'],
                        auth_name=auth_name,
                        headico=headico
                        )
        else:
            self.write('404，找不到该文章')

        # ArticleParser.getPageHTML(qiniu_url, path, base_url, title, refresh=True)
